/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lt.ntec.danblog.server.blog.model.objectify;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Set;
import lt.ntec.danblog.server.core.model.Tag;
import lt.ntec.danblog.server.core.model.TagDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Tadas
 */
class TagListProxy implements InvocationHandler {

    private static final Logger LOG =
            LoggerFactory.getLogger(TagListProxy.class);
    private Set<? extends Tag> tags;
    private final BlogPost blogPost;
    private final TagDAO tagDAO;

    public static Set<? extends Tag> newInstance(BlogPost blogPost,
                                                 TagDAO tagDAO) {
        return (Set<? extends Tag>) Proxy.newProxyInstance(Set.class.
                getClassLoader(), new Class[]{Set.class}, new TagListProxy(
                blogPost, tagDAO));
    }

    private TagListProxy(BlogPost blogPost, TagDAO tagDAO) {
        this.blogPost = blogPost;
        this.tagDAO = tagDAO;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws
            IllegalAccessException, IllegalArgumentException,
            InvocationTargetException {

        if (tags == null) {
            LOG.debug("Creating proxy");
            tags = tagDAO.getTagsByParent(blogPost);
        }

        LOG.debug("Delegating call for " + method.getName());

        return method.invoke(tags, args);
    }
}
